package com.jh.paymentchannel;

import cn.jh.common.exception.ApiExceptionHandler;
import cn.jh.common.interceptor.AuthenticationHeaderInterceptor;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


@SpringBootApplication
@EnableDiscoveryClient
@EnableTransactionManagement(proxyTargetClass = true)
public class PaymentChannelStartup extends WebMvcConfigurerAdapter {

	public static void main(String[] args) {
		new SpringApplicationBuilder(PaymentChannelStartup.class).run(args);
	}

	@Bean(initMethod = "init")
	public DruidDataSource dataSource() {
		return DruidDataSourceBuilder.create().build();
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new AuthenticationHeaderInterceptor()).addPathPatterns("/**");
	}

	@Bean
	public ApiExceptionHandler getApiExceptionHandler() {
		return new ApiExceptionHandler();
	}

	@Bean(name = "restTemplate")
	@Primary
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}

	/** 使用  http://{target:application.name}/request_uri 可以直接请求访问 service url */
	@Bean(name = "restOperations")
	@LoadBalanced
	public RestTemplate restOperations() {
		return new RestTemplate();
	}
}
